//
//  WBMainViewController.swift
//  微博
//
//  Created by Mstarc on 2016/11/28.
//  Copyright © 2016年 Mstarc. All rights reserved.
//

import UIKit

//主控制器
class WBMainViewController: UITabBarController {

    
    //定时器
    
     var timer:Timer?
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

       
       setupChildControllers()
       setupComposeBtn()
        setupTimer()
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
        //测试未读数量
        WBNetworkManager.shared().unreadCount { (count) in
            print("有 \(count) 条新微博")
        }
    }
    
    //销毁时钟
    deinit {
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    //portrait  :竖屏,肖像
    //landscape :横屏,风景画
    // - 使用代码控制设备的方向 ,好处:可以在需要横屏的时候单独处理
    // - 设置支持的方向之后,当前的控制器及子控制器都会遵循这个方向
    // - 如果是播放视屏 通常是用modal 展现的
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    //MARK: 监听方法
    
    @objc private func userLogin(n:Notification){
        //展示登录控制器 - 通常和UINavigationController连用 方便返回
        
        
        let nav = UINavigationController(rootViewController: WBOAuthController())
        present(nav, animated: true, completion: nil)
        
        print("用户登录通知:\(n)")
        
    }
    
    
    
    //FIXME: 没有实现
    //撰写微博
    func composeStatus() {
        print("撰写微博")
        //测试方向旋转
        let vc = UIViewController()
        let nav = UINavigationController(rootViewController: vc)
        vc.view.backgroundColor = UIColor.cz_random()
        present(nav, animated: true, completion: nil)
    }
    
    
    //MARK: - 私有控件
    //撰写按钮
     lazy var composeBtn: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")


}



// MARK: - UITabBarControllerDelegate
extension WBMainViewController:UITabBarControllerDelegate{
    
    /// 将要选择 TabbarItem
    ///
    /// - parameter tabBarController: tabBarController
    /// - parameter viewController:   目标控制器
    ///
    /// - returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到\(viewController)")
        //1.获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        
        //2.判断当前索引是首页,同时 idx 也是首页 ,重复点击首页按钮
        if selectedIndex == 0 && idx == selectedIndex {
            //3.让表格滚动到顶部
            //1>
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            vc.tabelView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            //刷新数据 - 增加延迟 ,保证tableView先滚动到顶部 在刷新
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: {
                vc.loadData()
            })
        }
        //判断目标控制器是否是 ViewController
        return !viewController.isMember(of: UIViewController.self)
    }
    
}

// MARK: - 时钟相关方法
extension WBMainViewController{
    //定义时钟
    func setupTimer()  {
        timer = Timer.scheduledTimer(timeInterval: 120.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    @objc private func updateTimer(){
        
        if !WBNetworkManager.shared().userLogin {
            return
        }
        
        WBNetworkManager.shared().unreadCount { (count) in
            print("检测到 \(count) 条新微博")
            
            //设置设置首页 tabBarItem 的 badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" :nil
            // 设置 app的 badgeNumber (需要用户授权才显示)
            
            UIApplication.shared.applicationIconBadgeNumber = count
            
            
        }
    }
}



//MARK: - 设置界面

//extension 类似于OC 中的分类,在swift中还可以切分代码块
//可以把相近功能的函数放在extension中
//便于代码维护
//注意: 和 OC 分类一样,extension中不能定义属性 只能定义方法

extension WBMainViewController{
    
    //设置撰写按钮
     func setupComposeBtn(){
        tabBar.addSubview(composeBtn)
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        //减一 是为了 处理容错点 (将向内缩进的宽度减少,能够让按钮的宽度变大,盖住容错点)
        let  w = tabBar.bounds.width / count
        //CGRectInset 正数向内缩进 ,负数向外扩展
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        //按钮监听方法
        composeBtn.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    
        
        
    }

    //设置所有子控制器
     func setupChildControllers() {
        
        //0.获取沙盒的文件路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        //判断data是否有内容,如果没有,说明本地沙盒没有文件
        if data == nil {
            //从bundle加载 data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
            
        }
        
      
        
        
        //从bundle加载配置的json
        //1.路径/2.加载 NSData 3.反序化转成数组
        guard
         
             let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String:AnyObject]]
            else{
                
            return
        }
   
        
        //在现有的很多应用程序中,界面的创建都依赖网络的json
//        let array:[[String:AnyObject]] = [
//            ["clsName":"WBHomeViewController" as AnyObject,"title":"首页" as AnyObject,"imageName":"home" as AnyObject,"visitorInfo":(["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]) as AnyObject],
//             ["clsName":"WBMessageViewController" as AnyObject,"title":"消息" as AnyObject,"imageName":"message_center" as AnyObject
//            ,"visitorInfo":(["imageName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]) as AnyObject
//            ],
//             ["clsName":"xx" as AnyObject],
//            ["clsName":"WBDiscoverViewController" as AnyObject,"title":"发现" as AnyObject,"imageName":"discover" as AnyObject,"visitorInfo":(["imageName":"visitordiscover_image_message","message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]) as AnyObject
//            ],
//        ["clsName":"WBProfileViewController" as AnyObject,"title":"我" as AnyObject,"imageName":"profile" as AnyObject,"visitorInfo":(["imageName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]) as AnyObject
//            ]
//        ]
//        //数组 -> json 序列化
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        
//        (data as NSData).write(toFile: "/Users/Mstarc/Desktop/demo.json", atomically: true)
//        
        //遍历数组,循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        //设置tabbar 的子控制器
        viewControllers = arrayM
    }
  
    //使用字典创建一个子控制器
    // - parameter dict:信息字典
    // - return: 自控制器
    
    private func controller(dict:[String:AnyObject]) ->UIViewController {
       
        //1.取得字典内容
        
        guard let clsName = dict["clsName"] as? String,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseController.Type,
            let visitorDict = dict["visitorInfo"]
            
            else {
            return UIViewController()
        }
        //2.创建视图控制器
        let vc = cls.init()
        vc.title = title
        //设置控制器的访客信息字典
        vc.visitorInfoDict = visitorDict as? [String : String]
        
        //3.创建图片
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        
        //4设置标题字体  ,系统默认是12号字,设置字体大小要设置在normal
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
        //实例化导航控制器上时候 ,会调用push方法 rootVC 压栈
        let nav = WBNavigationController(rootViewController: vc)
        return nav
 
        
    }
    
    
    
}
